/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.ohosannotations.internal.core.handler;

import com.helger.jcodemodel.AbstractJClass;
import com.helger.jcodemodel.IJAssignmentTarget;
import com.helger.jcodemodel.IJExpression;
import com.helger.jcodemodel.JBlock;
import com.helger.jcodemodel.JFieldRef;
import com.helger.jcodemodel.JInvocation;

import org.ohosannotations.ElementValidation;
import org.ohosannotations.OhosAnnotationsEnvironment;
import org.ohosannotations.annotations.SystemService;
import org.ohosannotations.handler.BaseAnnotationHandler;
import org.ohosannotations.handler.MethodInjectionHandler;
import org.ohosannotations.helper.CanonicalNameConstants;
import org.ohosannotations.helper.InjectHelper;
import org.ohosannotations.holder.EComponentHolder;
import org.ohosannotations.internal.core.model.OhosSystemServices;

import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.TypeMirror;

import static com.helger.jcodemodel.JExpr._new;

/**
 * 系统服务处理程序
 *
 * @author dev
 * @since 2021-07-22
 */
public class SystemServiceHandler extends BaseAnnotationHandler<EComponentHolder>
    implements MethodInjectionHandler<EComponentHolder> {
    private final InjectHelper<EComponentHolder> injectHelper;

    /**
     * 系统服务处理程序
     *
     * @param environment 环境
     */
    public SystemServiceHandler(OhosAnnotationsEnvironment environment) {
        super(SystemService.class, environment);
        injectHelper = new InjectHelper<>(validatorHelper, this);
    }

    /**
     * 验证
     *
     * @param element 元素
     * @param validation 验证
     */
    @Override
    public void validate(Element element, ElementValidation validation) {
        injectHelper.validate(SystemService.class, element, validation);
        if (!validation.isValid()) {
            return;
        }

        validatorHelper.ohosService(element, validation);

        validatorHelper.isNotPrivate(element, validation);
    }

    /**
     * 过程
     *
     * @param element 元素
     * @param holder 持有人
     */
    @Override
    public void process(Element element, EComponentHolder holder) {
        injectHelper.process(element, holder);
    }

    /**
     * 得到调用块
     *
     * @param holder 持有人
     * @return {@link JBlock}
     */
    @Override
    public JBlock getInvocationBlock(EComponentHolder holder) {
        return holder.getInitBodyInjectionBlock();
    }

    /**
     * 赋值
     *
     * @param targetBlock 目标块
     * @param fieldRef 现场裁判
     * @param holder 持有人
     * @param element 元素
     * @param param 参数
     */
    @Override
    public void assignValue(JBlock targetBlock, IJAssignmentTarget fieldRef,
        EComponentHolder holder, Element element, Element param) {
        TypeMirror serviceType = param.asType();
        String fieldTypeQualifiedName = serviceType.toString();
        JFieldRef serviceRef = new OhosSystemServices(getEnvironment()).getServiceConstantRef(serviceType);
        if (CanonicalNameConstants.BLUETOOTH_HOST.equals(fieldTypeQualifiedName)) {
            targetBlock.add(fieldRef.assign(createBluetoothInjection(holder, fieldTypeQualifiedName, serviceRef)));
        } else if (CanonicalNameConstants.USB_CORE.equals(fieldTypeQualifiedName)) {
            targetBlock.add(fieldRef.assign(createUsbInjection(holder, fieldTypeQualifiedName, serviceRef)));
        } else if (CanonicalNameConstants.ABILITY_MANAGER.equals(fieldTypeQualifiedName)) {
            targetBlock.add(fieldRef.assign(createAbilityManagerInjection(holder, fieldTypeQualifiedName, serviceRef)));
        } else if (CanonicalNameConstants.WINDOW_MANAGER.equals(fieldTypeQualifiedName)) {
            targetBlock.add(fieldRef.assign(createWindowManagerInjection(holder, fieldTypeQualifiedName, serviceRef)));
        } else {
            targetBlock.add(fieldRef.assign(createNormalInjection(holder, fieldTypeQualifiedName, serviceRef)));
        }
    }

    /**
     * 创建窗口管理器注入
     *
     * @param holder 持有人
     * @param fieldTypeQualifiedName 字段类型限定名称
     * @param serviceRef 服务裁判
     * @return {@link IJExpression}
     */
    private IJExpression createWindowManagerInjection(EComponentHolder holder,
        String fieldTypeQualifiedName, JFieldRef serviceRef) {
        AbstractJClass sysCls = getJClass(fieldTypeQualifiedName);
        JInvocation out = sysCls.staticInvoke("getInstance");
        return out;
    }

    /**
     * 创造能力管理注入
     *
     * @param holder 持有人
     * @param fieldTypeQualifiedName 字段类型限定名称
     * @param serviceRef 服务裁判
     * @return {@link IJExpression}
     */
    private IJExpression createAbilityManagerInjection(EComponentHolder holder,
        String fieldTypeQualifiedName, JFieldRef serviceRef) {
        return holder.getContextRef().invoke("getAbilityManager");
    }

    /**
     * 创建usb注入
     *
     * @param holder 持有人
     * @param fieldTypeQualifiedName 字段类型限定名称
     * @param serviceRef 服务裁判
     * @return {@link IJExpression}
     */
    private IJExpression createUsbInjection(EComponentHolder holder,
        String fieldTypeQualifiedName, JFieldRef serviceRef) {
        AbstractJClass sysCls = getJClass(fieldTypeQualifiedName);
        return _new(sysCls).arg(holder.getContextRef());
    }

    /**
     * 创建蓝牙注入
     *
     * @param holder 持有人
     * @param fieldTypeQualifiedName 字段类型限定名称
     * @param serviceRef 服务裁判
     * @return {@link IJExpression}
     */
    private IJExpression createBluetoothInjection(EComponentHolder holder,
        String fieldTypeQualifiedName, JFieldRef serviceRef) {
        AbstractJClass sysCls = getJClass(fieldTypeQualifiedName);
        JInvocation out = sysCls.staticInvoke("getDefaultHost").arg(holder.getContextRef());
        return out;
    }

    /**
     * 创建正常注入
     *
     * @param holder 持有人
     * @param fieldTypeQualifiedName 字段类型限定名称
     * @param serviceRef 服务裁判
     * @return {@link IJExpression}
     */
    private IJExpression createNormalInjection(EComponentHolder holder,
        String fieldTypeQualifiedName, JFieldRef serviceRef) {
        AbstractJClass sysCls = getJClass(fieldTypeQualifiedName);
        JInvocation out = sysCls.staticInvoke("getInstance").arg(holder.getContextRef());
        return out;
    }

    /**
     * api在类路径中
     *
     * @param apiName api名称
     * @return boolean
     */
    private boolean isApiOnClasspath(String apiName) {
        TypeElement typeElement = getProcessingEnvironment().getElementUtils()
            .getTypeElement(CanonicalNameConstants.BUILD_VERSION_CODES);
        for (Element element : typeElement.getEnclosedElements()) {
            if (element.getSimpleName().contentEquals(apiName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 验证封装元素
     *
     * @param element 元素
     * @param valid 有效的
     */
    @Override
    public void validateEnclosingElement(Element element, ElementValidation valid) {
        validatorHelper.enclosingElementHasEnhancedComponentAnnotation(element, valid);
    }
}
